package vn.vfriends.vcms.site.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vcms.site.model.Device;

/**
 *
 * @author tuan@vfriends.vn
 */
@WebFilter(filterName="DeviceDetectionFilter", urlPatterns="/*")
public class DeviceDetectionFilter implements Filter {
    
    private final Logger logger = LoggerFactory.getLogger(DeviceDetectionFilter.class);
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest) request;
        String userAgent = hreq.getHeader("User-Agent");
        logger.info("User-Agent: " + userAgent);
        
        Device device = null;
        
        if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("iphone") >= 0) {
            device = Device.iOS;
        } else if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("ipad") >= 0) {
            device = Device.iOS;
        } else if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("ipod") >= 0) {
            device = Device.iOS;
        } else if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("android") >= 0) {
            device = Device.Android;
        } else if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("blackberry") >= 0) {
            device = Device.BlackBerry;
        } else if(!StringUtils.isEmpty(userAgent) && userAgent.toLowerCase().indexOf("windows phone") >= 0) {
            device = Device.WindowsPhone;
        } else {
            device = Device.Other;
        }
        
        
        HttpSession session = hreq.getSession(true);
        session.setAttribute("DEVICE", device);
        //String userAgent = request.getu
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {}
}
